package com.itheima.chap02;

public class URLParseDemo {
    public static void main(String[] args) {
        String url = "https://s.taobao.com/search?q=Xiaomi12x&page=1&tap=mall";
        pareseURL(url);
    }

    public static void pareseURL(String url) {
    // 1.解析协议
    int protocolEndIndex = url.indexOf("://");
    if(protocolEndIndex < 0){
        System.out.println("URl格式错误");
        return;
    }
    String protocol = url.substring(0, protocolEndIndex);
    System.out.println("协议：" + protocol);
    // 2.解析域名
    int hostEndIndex = url.indexOf("/", protocolEndIndex + 3);
    if(hostEndIndex < 0){
        System.out.println("URl格式错误");
        return;
    }
    String host = url.substring(protocolEndIndex + 3, hostEndIndex);
    System.out.println("域名：" + host);
    // 3.解析请求路径
    int pathEndIndex = url.indexOf("?", hostEndIndex);
    if(pathEndIndex < 0){
        System.out.println("URl格式错误");
        return;
    }
    String path = url.substring(hostEndIndex, pathEndIndex);
    System.out.println("请求路径：" + path);
    // 4.解析请求参数
    String query = url.substring(pathEndIndex + 1); //q=Xiaomi12x&page=1&tap=mall
        String[] params = query.split("&");
        for (int i = 0; i < params.length; i++) {
            String param = params[i];
            String[] arr = param.split("=");
            System.out.println(arr[0] + " : " + arr[1]);
        }
    }
}
